package com.xnx3.banmahuishou.userApplet.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xnx3.StringUtil;
import com.xnx3.banmahuishou.core.service.PriceService;
import com.xnx3.banmahuishou.core.vo.PriceVO;
import com.xnx3.banmahuishou.userApplet.vo.CartVO;
import com.xnx3.j2ee.controller.BaseController;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.SafetyUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.wangmarket.shop.core.entity.Address;
import com.xnx3.wangmarket.shop.core.entity.Goods;
import com.xnx3.wangmarket.shop.core.entity.GoodsType;
import com.xnx3.wangmarket.shop.core.entity.OrderGoods;
import com.xnx3.wangmarket.shop.core.service.CartService;

/**
 * 斑马回收用户端，订单创建前的购物车这方面
 * @author 管雷鸣
 */
@Controller(value="BanmahuishouUserAppletCartController")
@RequestMapping("/userApplet/cart/")
public class CartController extends BaseController{
	@Resource
	private UserService userService;
	@Resource
	private SqlCacheService sqlCacheService;
	@Resource
	private SqlService sqlService;
	@Resource
	private CartService cartService;
	@Resource
	private PriceService priceService;
	
	
	/**
	 * 获取购物车中设置的上门取件地址
	 * @param id 地址ID
	 * @param username 收货人名字
	 * @param phone 收货人电话
	 * @param sex 性别，1先生，2女士
	 * @param address 收货人地址
	 * @param sheng 所在的省,如： 山东省
	 * @param shi 所在的市，如 潍坊市
	 * @param qu 所在的区，如 寒亭区
	 * @param house 具体房间号，如 17号楼2单元202室
	 * @param longitude 经纬度，如 12.223344
	 * @param latitude 经纬度，如 12.223344
	 * @author 管雷鸣
	 */
	@RequestMapping(value="setAddress.json",method = {RequestMethod.POST})
	@ResponseBody
	public CartVO setAddress(HttpServletRequest request,
			@RequestParam(value = "id", required = false, defaultValue = "") Integer id,
			@RequestParam(value = "username", required = false, defaultValue = "") String username,
			@RequestParam(value = "phone", required = false, defaultValue = "") String phone,
			@RequestParam(value = "sex", required = false, defaultValue = "") Short sex,
			@RequestParam(value = "address", required = false, defaultValue = "") String address,
			@RequestParam(value = "sheng", required = false, defaultValue = "") String sheng,
			@RequestParam(value = "shi", required = false, defaultValue = "") String shi,
			@RequestParam(value = "qu", required = false, defaultValue = "") String qu,
			@RequestParam(value = "house", required = false, defaultValue = "") String house,
			@RequestParam(value = "isDefault", required = false, defaultValue = "") String isDefault,
			@RequestParam(value = "longitude", required = false, defaultValue = "0") Double longitude,
			@RequestParam(value = "latitude", required = false, defaultValue = "0") Double latitude){
		
		//获取当前缓存
		CartVO vo = cartService.getCurrentUserCacheCartVO();
		
		Address newAddress = new Address();
		//设置数据
		newAddress.setUsername(SafetyUtil.xssFilter(username));
		newAddress.setPhone(SafetyUtil.xssFilter(phone));
		newAddress.setSex(sex);
		newAddress.setAddress(StringUtil.filterXss(address.replaceAll("\\(", "（").replaceAll("\\)", "）")));
		newAddress.setSheng(SafetyUtil.xssFilter(sheng));
		newAddress.setShi(SafetyUtil.xssFilter(shi));
		newAddress.setQu(SafetyUtil.xssFilter(qu));
		newAddress.setHouse(SafetyUtil.xssFilter(house));
		newAddress.setLongitude(longitude);
		newAddress.setLatitude(latitude);
		newAddress.setUserid(getUserId());
		newAddress.setId(id);
		//判断isDefault是否传入值
		isDefault = isDefault.trim();
		if(isDefault.length() > 0) {
			//默认地址有变动
			if(isDefault.equals("1")){
				//再将传入的地址设为默认
				newAddress.setDefaultUse((short) 1);
			}else if(isDefault.equals("0")){
				// 将该地址设为非默认地址
				newAddress.setDefaultUse((short) 0);
			}
		}
		vo.setAddress(newAddress);
		//更新缓存
		cartService.setCurrentUserCacheCartVO(vo);
		
		ActionLogUtil.insertUpdateDatabase(request, "设置购物车中的地址");
		return vo;
	}
	
	
	/**
	 * 向当前的购物车中设置一个商品（增加）
	 * @param goodsid 要设置商品的id，对应goods.id
	 * @param weight 要设置商品的重量，注意单位是g
	 * @return
	 * @author 管雷鸣
	 */
	@RequestMapping(value="setGoods.json",method = {RequestMethod.POST})
	@ResponseBody
	public CartVO setGoods(HttpServletRequest request,
			@RequestParam(required = false, defaultValue = "29") int goodsid,
			@RequestParam(required = false, defaultValue = "1000") int weight){
		//获取当前缓存
		CartVO vo = cartService.getCurrentUserCacheCartVO();
		User user = sqlService.findById(User.class, getUserId());
		if(user == null) {
			CartVO errorVO = new CartVO();
			errorVO.setBaseVO(BaseVO.FAILURE, "请重新扫码登录");
			return errorVO;
		}
		Goods goods = sqlService.findById(Goods.class, goodsid);
		if(goods == null) {
			CartVO errorVO = new CartVO();
			errorVO.setBaseVO(BaseVO.FAILURE, "商品不存在");
			return errorVO;
		}
		GoodsType goodsType = sqlService.findById(GoodsType.class, goods.getTypeid());
		if(goodsType == null) {
			CartVO errorVO = new CartVO();
			errorVO.setBaseVO(BaseVO.FAILURE, "大类不存在");
			return errorVO;
		}
		
		List<OrderGoods> list = deleteGoodsByOrderGoodsList(vo.getOrderGoodsList(), goodsid);
		OrderGoods orderGoods = new OrderGoods();
		orderGoods.setGoodsid(goods.getId());
		orderGoods.setGoodsTypeId(goods.getTypeid());
		orderGoods.setGoodsTypeName(goodsType.getTitle());
		
		//计算价格，获取预估价
		int dlsUserid = user.getDailishangUserid() == null ? 0 : user.getDailishangUserid();
		PriceVO priceVO = priceService.getPriceByGoodsTypeId(goodsType.getId(),dlsUserid);
		if(priceVO.getResult() - PriceVO.FAILURE == 0) {
			CartVO errorVO = new CartVO();
			errorVO.setBaseVO(BaseVO.FAILURE, priceVO.getInfo());
			return errorVO;
		}
		orderGoods.setMaxMoney(priceVO.getMaxPrice());
		orderGoods.setMinMoney(priceVO.getMinPrice());
		orderGoods.setPrice(priceVO.getPrice());
		
		/*
		 * 最小重量跟最大重量，待确认
		 */
		orderGoods.setMinWeight(weight);
		orderGoods.setMaxWeight(weight);
		
		orderGoods.setNumber(weight);
		orderGoods.setMoney((orderGoods.getPrice() * orderGoods.getNumber()) / 1000 ); //设置该商品预估的金额
		orderGoods.setTitle(goods.getTitle());
		orderGoods.setTitlepic(goods.getTitlepic());
		orderGoods.setUnits(goods.getUnits());
		orderGoods.setUserid(getUserId());
		list.add(orderGoods);
		
		//更新缓存
		cartService.setCurrentUserCacheCartVO(vo);
		
		ActionLogUtil.insertUpdateDatabase(request, "向当前的购物车中设置一个商品");
		return vo;
	}
	
	
	/**
	 * 向当前的购物车中设置一个大类（下单填写-添加废品使用）
	 * <p>因为设置的是大类，默认将大类下的第一个商品加入进去。免得进入用户小程序的分类页面，不知道显示那个商品了</p>
	 * @param goodsTypeId 要添加废品id，对应goodsType.id
	 * @param weight 	选择的商品重量的平均值，注意单位是g
	 * @param minWeight 选择的商品重量的最小值，注意单位是g
	 * @param maxWeight 选择的商品重量的最大值，注意单位是g
	 * @return
	 * @author 管雷鸣
	 */
	@RequestMapping(value="setGoodsType.json",method = {RequestMethod.POST})
	@ResponseBody
	public CartVO setGoodsType(HttpServletRequest request,
			@RequestParam(required = false, defaultValue = "12") int goodsTypeId,
			@RequestParam(required = false, defaultValue = "17500") int weight,
			@RequestParam(required = false, defaultValue = "10000") int minWeight,
			@RequestParam(required = false, defaultValue = "25000") int maxWeight){
		//获取当前缓存
		CartVO vo = cartService.getCurrentUserCacheCartVO();
		User user = sqlService.findById(User.class, getUserId());
		if(user == null) {
			CartVO errorVO = new CartVO();
			errorVO.setBaseVO(BaseVO.FAILURE, "请重新扫码登录");
			return errorVO;
		}
		//获取分类信息
		GoodsType goodsType = sqlService.findById(GoodsType.class, goodsTypeId);
		if(goodsType == null) {
			CartVO errorVO = new CartVO();
			errorVO.setBaseVO(BaseVO.FAILURE, "大类不存在");
			return errorVO;
		}
		//获取分类下的第一个商品
		Goods goods = sqlService.findAloneBySqlQuery("SELECT * FROM shop_goods WHERE typeid = "+goodsTypeId+" ORDER BY rank ASC LIMIT 1", Goods.class);
		
		/**** 从列表中删除该分类的信息，以免重复 ****/
		List<OrderGoods> list = vo.getOrderGoodsList();
		int deletei = -1;	//要从list中删除的i下标
		for (int i = 0; i < list.size(); i++) {
			OrderGoods orderGoods = list.get(i);
			if(orderGoods.getGoodsTypeId() - goodsTypeId == 0) {
				deletei = i;
				break;
			}
		}
		if(deletei > -1) {
			list.remove(deletei);
		}
		
		/**** 组合信息 ****/
		OrderGoods orderGoods = new OrderGoods();
		if(goods != null) {
			orderGoods.setGoodsid(goods.getId());
			orderGoods.setTitle(goods.getTitle());
			orderGoods.setTitlepic(goods.getTitlepic());
			orderGoods.setUnits(goods.getUnits());
		}
		
		orderGoods.setGoodsTypeId(goods.getTypeid());
		orderGoods.setGoodsTypeName(goodsType.getTitle());

		//计算价格，获取预估价
		int dlsUserid = user.getDailishangUserid() == null ? 0 : user.getDailishangUserid();
		PriceVO priceVO = priceService.getPriceByGoodsTypeId(goodsType.getId(),dlsUserid);
		if(priceVO.getResult() - PriceVO.FAILURE == 0) {
			CartVO errorVO = new CartVO();
			errorVO.setBaseVO(BaseVO.FAILURE, priceVO.getInfo());
			return errorVO;
		}
		orderGoods.setMaxMoney(priceVO.getMaxPrice());
		orderGoods.setMinMoney(priceVO.getMinPrice());
		orderGoods.setPrice(priceVO.getPrice());
		
		//最大重量、最小重量，待定
		orderGoods.setMinWeight(minWeight);
		orderGoods.setMaxWeight(maxWeight);
		orderGoods.setNumber(weight);
		orderGoods.setMoney((orderGoods.getPrice() * orderGoods.getNumber()) / 1000 ); //设置该商品预估的金额
		orderGoods.setUserid(getUserId());
		list.add(orderGoods);
		
		//更新缓存
		vo.setOrderGoodsList(list);
		cartService.setCurrentUserCacheCartVO(vo);
		
		ActionLogUtil.insertUpdateDatabase(request, "向当前的购物车中设置一个大类");
		return vo;
	}
	

	/**
	 * 再当前购物车中减去一个分类。
	 * @param goodsTypeId 要减去废品大类的id，对应goodsType.id
	 * @author 管雷鸣
	 */
	@RequestMapping(value="deleteGoodsType.json",method = {RequestMethod.POST})
	@ResponseBody
	public CartVO deleteGoodsType(HttpServletRequest request,
			@RequestParam(required = false, defaultValue = "12") int goodsTypeId){
		//获取当前缓存
		CartVO vo = cartService.getCurrentUserCacheCartVO();
		
		/**** 从列表中删除该分类的信息 ****/
		List<OrderGoods> list = vo.getOrderGoodsList();
		int deletei = -1;	//要从list中删除的i下标
		for (int i = 0; i < list.size(); i++) {
			OrderGoods orderGoods = list.get(i);
			if(orderGoods.getGoodsTypeId() - goodsTypeId == 0) {
				deletei = i;
				break;
			}
		}
		if(deletei > -1) {
			list.remove(deletei);
		}
		
		vo.setOrderGoodsList(list);
		//更新缓存
		cartService.setCurrentUserCacheCartVO(vo);
		
		ActionLogUtil.insertUpdateDatabase(request, "再当前购物车中减去一个分类。");
		return vo;
	}
	

	/**
	 * 获取当前的购物车信息.
	 * <p>如果当前用户还没往购物车的地址中设置信息，那取用户自己设置的默认地址赋予。如果也没有默认地址，那就空了。。</p>
	 * @author 管雷鸣
	 */
	@RequestMapping(value="getCart.json",method = {RequestMethod.POST})
	@ResponseBody
	public CartVO setGoods(HttpServletRequest request){
		//获取当前缓存
		CartVO vo = cartService.getCurrentUserCacheCartVO();
		
		//如果当前购物车缓存地址中没有，那默认取用户设置的默认地址赋予
		if(vo.getAddress() == null) {
			User user = getUser();
			Address defaultAddress = sqlService.findAloneBySqlQuery("SELECT * FROM shop_address WHERE userid = "+user.getId()+" AND default_use = 1", Address.class);
			if(defaultAddress != null) {
				Address address = new Address();
				BeanUtils.copyProperties(defaultAddress, address);	//bean复制
				vo.setAddress(address);
			}else {
				//如果没有设置的默认地址，那就new一个
				vo.setAddress(new Address());
			}
			
			//更新缓存
			cartService.setCurrentUserCacheCartVO(vo);
		}
		
		ActionLogUtil.insertUpdateDatabase(request, "获取当前的购物车信息.");
		return vo;
	}
	

	/**
	 * 清空当前的购物车所有商品
	 * @author 管雷鸣
	 */
	@RequestMapping(value="clearGoods.json",method = {RequestMethod.POST})
	@ResponseBody
	public CartVO clearGoods(HttpServletRequest request){
		//获取当前缓存
		CartVO vo = cartService.getCurrentUserCacheCartVO();
		vo.setOrderGoodsList(new ArrayList<OrderGoods>());
		
		//更新缓存
		cartService.setCurrentUserCacheCartVO(vo);
		
		ActionLogUtil.insertUpdateDatabase(request, "清空当前的购物车所有商品");
		return vo;
	}
	
	
	/**
	 * 从商品列表中，删除制定的某个商品。将删除后的list返回
	 * @param list
	 * @param deleteGoodsId 要删除的goods.id
	 * @return
	 */
	private List<OrderGoods> deleteGoodsByOrderGoodsList(List<OrderGoods> list, int deleteGoodsId){
		int deletei = -1;	//要从list中删除的i下标
		for (int i = 0; i < list.size(); i++) {
			OrderGoods orderGoods = list.get(i);
			if(orderGoods.getGoodsid() - deleteGoodsId == 0) {
				deletei = i;
				break;
			}
		}
		
		if(deletei > -1) {
			list.remove(deletei);
		}
		return list;
	}
	
}
